package org.breathe.dynamic.thread.pool.core.monitor.endpoint;

import cn.hutool.core.io.FileUtil;
import cn.hutool.system.RuntimeInfo;
import com.google.common.collect.Lists;
import org.breathe.dynamic.thread.pool.core.convert.MetricsConverter;
import org.breathe.dynamic.thread.pool.core.executor.ThreadPoolExecutorRegistry;
import org.breathe.thread.pool.common.entity.JvmStats;
import org.breathe.thread.pool.common.entity.Metrics;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

import java.util.List;

/**
 * 动态线程池切入点
 * @author: breathe
 * @createTime: 2025-04-14
 */
@Endpoint(id = "breathe-dynamic-tp")
public class BreatheDtpEndpoint {
    @ReadOperation
    public List<Metrics> invoke() {
        List<String> dtpNames = ThreadPoolExecutorRegistry.listAllBreatheDtpNames();
        List<Metrics> metricsList = Lists.newArrayList();
        dtpNames.stream()
                .map(ThreadPoolExecutorRegistry::get)
                .map(MetricsConverter::convert)
                .forEach(metricsList::add);
        JvmStats jvmStats = new JvmStats();
        RuntimeInfo runtimeInfo = new RuntimeInfo();
        jvmStats.setMaxMemory(FileUtil.readableFileSize(runtimeInfo.getMaxMemory()));
        jvmStats.setTotalMemory(FileUtil.readableFileSize(runtimeInfo.getTotalMemory()));
        jvmStats.setFreeMemory(FileUtil.readableFileSize(runtimeInfo.getFreeMemory()));
        jvmStats.setUsableMemory(FileUtil.readableFileSize(runtimeInfo.getUsableMemory()));
        metricsList.add(jvmStats);
        return metricsList;
    }
}
